<template>
  <div class="sales-orders-container">
    <h1 class="title">销售订单列表</h1>
    <div class="button-group">
      <el-button type="primary" @click="addOrder" class="add-button">添加新销售订单</el-button>
      <el-button type="success" @click="exportSalesReport" class="export-button">导出销售订单报表</el-button>
    </div>
    <el-table :data="orders" style="width: 100%" border>
      <el-table-column prop="id" label="订单 ID" width="120" align="center" />
      <el-table-column prop="customer_name" label="客户名称" width="150" />
      <el-table-column label="订单日期" width="150" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.order_date) }}
        </template>
      </el-table-column>
      <el-table-column label="销售明细" align="center" width="300">
        <template #default="scope">
          <el-table :data="scope.row.sales_detail" style="width: 100%" border>
            <el-table-column prop="quantity" label="数量" width="90" />
            <el-table-column prop="unit_price" label="单价(元)" width="90" />
            <el-table-column prop="goods_name" label="商品" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column prop="total_amount" label="总金额" width="150" />
      <el-table-column prop="status_cn" label="状态" width="100"/>
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-button size="small" @click="editOrder(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteOrder(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑状态弹窗保持不变 -->
    <el-dialog v-model="editDialogVisible" title="编辑订单状态" width="30%">
      <el-form :model="currentOrder" label-width="100px">
        <el-form-item label="订单状态">
          <el-select v-model="currentOrder.status" placeholder="请选择状态">
            <el-option label="待处理" :value="'pending'" />
            <el-option label="已发货" :value="'shipped'" />
            <el-option label="已完成" :value="'completed'" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getSalesOrders, deleteSalesOrder, updateSalesOrder, generateSalesReport } from '@/api/salesOrders';
import {ref, onMounted} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';

export default {
  setup() {
    const orders = ref([]);
    const router = useRouter();
    const editDialogVisible = ref(false);
    const currentOrder = ref(null);

    const formatDate = (date) => {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
    };

    const fetchSalesOrders = async () => {
      try {
        const response = await getSalesOrders();
        orders.value = response.data;
      } catch (error) {
        console.error('Error fetching sales orders:', error);
      }
    };

    const deleteOrderById = async (id) => {
      try {
        await deleteSalesOrder(id);
        ElMessage.success('删除成功');
        fetchSalesOrders(); // 更新销售订单列表
      } catch (error) {
        console.error('Error deleting sales order:', error);
        ElMessage.error('删除失败');
      }
    };

    const editOrder = (order) => {
      currentOrder.value = {...order};
      editDialogVisible.value = true;
    };

    const confirmEdit = async () => {
      try {
        await updateSalesOrder(currentOrder.value.id, currentOrder.value.status);
        ElMessage.success('状态更新成功');
        editDialogVisible.value = false;
        fetchSalesOrders(); // 更新销售订单列表
      } catch (error) {
        console.error('Error updating sales order status:', error);
        ElMessage.error('状态更新失败');
      }
    };

    const addOrder = () => {
      router.push('/sales/orders/add'); // 导航到添加销售订单的页面
    };


    // 新增导出报表功能
    const exportSalesReport = async () => {
      try {
        await generateSalesReport();
        ElMessage.success('销售订单报表导出成功，请前往报表管理下载。');
      } catch (error) {
        ElMessage.error('销售订单报表导出失败，请稍后重试。');
        console.error('Failed to export sales report:', error);
      }

    };

    onMounted(fetchSalesOrders);

    return {
      orders,
      formatDate,
      deleteOrder: deleteOrderById,
      editOrder,
      addOrder,
      editDialogVisible,
      currentOrder,
      confirmEdit,
      exportSalesReport, // 返回新增的方法
    };
  }
};
</script>

<style scoped>
.sales-orders-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.add-button, .export-button {
  margin: 0 10px;
}

.el-table {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.el-table th.el-table__cell {
  background-color: #f5f7fa;
  color: #303133;
  font-weight: bold;
  text-align: center !important;
}

.el-table td.el-table__cell {
  text-align: center;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}
</style>